<template>
  <el-dialog
    width="500px"
    :title="{ add: '新增部门', lock: '编辑部门' }[mode]"
    :visible.sync="isShow"
    @close="closeEvent"
  >
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
        <!-- <el-input v-model="form.manager" /> -->
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="isShow = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments.js'
export default {
  props: ['initData'],
  data () {
    return {
      isShow: false,
      //   下拉人员列表
      userList: [],
      value: '',
      mode: 'add', //  add:新增   lock: 编辑
      form: {
        name: '', // 部门名称
        code: '', // 部门编码，同级部门不可重复
        manager: '', // 负责人名称
        introduce: '', // 介绍
        pid: '' // 父级部门ID
      },
      rules: {
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            //   部门名称自定义表单验证
            validator: (rules, value, callback) => {
              // 找到当前点击项的子集部门
              const result = this.initData.filter(item => {
                if (this.mode === 'add') {
                  return item.pid === this.form.pid
                } else if (this.mode === 'lock') {
                  // 编辑时的name表单验证处理
                  return item.pid === this.form.pid && item.id !== this.form.id
                }
              })
              //   判断做部门名称是否重复的匹配
              const resultBol = result.some(item => {
                return item.name === value
              })
              resultBol
                ? callback(new Error(`部门名称不能重复:${value}`))
                : callback()
            }
          }
        ],
        code: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            validator: (rules, value, callback) => {
              //   判断部门编码是否重复
              const codeBol = this.initData.some(item => {
                if (this.mode === 'add') {
                  return item.code === value
                } else if (this.mode === 'lock') {
                  // 编辑code的表单验证
                  return item.code === value && item.id !== this.form.id
                }
              })
              codeBol
                ? callback(new Error(`部门编码重复:${value}`))
                : callback()
            }
          }
        ],
        manager: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        introduce: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted () {
    //   bus监听
    this.$bus.$on('openAdd', (bol, data, mode) => {
      this.isShow = bol
      this.form.pid = data.id
      this.mode = mode
      // 点击编辑时才回显数据
      if (mode === 'lock') {
        // 只有编辑时才数据深拷贝
        this.form = JSON.parse(JSON.stringify(data))
      }
    })
  },
  //   bus销毁
  beforeDestroy () {
    this.$bus.$off('openAdd')
  },
  methods: {
    closeEvent () {
      //   console.log('closeEvent')
      //   关闭弹框
      this.isShow = false
      // 重置表单数据与清空表单验证
      this.$refs.form.resetFields()
      // 重置表单数据
      this.form = {
        name: '', // 部门名称
        code: '', // 部门编码，同级部门不可重复
        manager: '', // 负责人名称
        introduce: '', // 介绍
        pid: '' // 父级部门ID
      }
    },
    // 点击确认后触发表单验证
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            // 添加表单数据
            await companyDepartmentPost(this.form)
            this.$message.success('新增成功')
          } else if (this.mode === 'lock') {
            // 添加表单数据
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          // 关闭表单和请求输入框的内容 & 关闭弹窗
          this.closeEvent()
          //   刷新父级列表数据
          this.$emit('getBranch')
        }
      })
    },
    // select获取焦点时调用接口
    async focusEvent () {
      // 判断是否有数据，没有数据时才调用存储
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
        console.log(res)
      }
    }
  }
}
</script>

<style></style>
